/*
 * reddirect
 * automatic redirection for sites that don't work with reddit toolbar
 *
 * by Minsang Kim
 * http://minsang.wordpress.com
 *
 * Copyright (c) 2011 Minsang Kim. All rights reserved.
 */

// window.location.pathname is something like /tb/abcde
var fullname = window.location.pathname.split("/")[2];

function matched(expected, actual) {
    // TODO: option to use regex instead of substring matching
    return actual.indexOf(expected) !== -1;
}

$.getJSON("http://www.reddit.com/by_id/t3_" + fullname + ".json", function(data) {
    var url = data.data.children[0].data.url;
    var domain = data.data.children[0].data.domain;
    
    // Get list of sites
    chrome.extension.sendRequest({type: "sites"}, function(response) {
        if (!response) {
            return;
        }
        
        var whitelist = response.whitelist;
        var blacklist = response.blacklist;
        
        var in_whitelist = false;
        
        // check whitelist first
        for (var i = 0; i < whitelist.length; i++) {
            if (matched(whitelist[i], domain)) {
                in_whitelist = true;
                break;
            }
        }
        
        // don't check blacklist if found in whitelist
        if (in_whitelist) {
            return;
        }
        
        // finally check blacklist and do redirect
        for (var i = 0; i < blacklist.length; i++) {
            if (matched(blacklist[i], domain)) {
                window.location.replace(url);
                break;
            }
        }
    });
});
